package cn.iocoder.yudao.module.ao.service.schedule;

// import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
// import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
// import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import java.util.stream.Collectors;
import cn.iocoder.yudao.module.ao.controller.admin.schedule.vo.*;
import cn.iocoder.yudao.module.ao.dal.dataobject.schedule.ScheduleDO;
// import cn.iocoder.yudao.framework.common.pojo.PageResult;
// import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.ao.dal.mysql.schedule.ScheduleMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.ao.enums.ErrorCodeConstants.*;

/**
 * 课程安排 Service 实现类
 *
 * @author 小y
 */
@Service
@Validated
public class ScheduleServiceImpl implements ScheduleService {

    @Resource
    private ScheduleMapper scheduleMapper;
    
    // @Resource
    // private AdminUserApi adminUserApi;

    /* 
     * ============================================================
     * 以下方法已废弃 - 不适用于新的 jx_senior_vocational_class_schedule 表结构
     * 旧方法使用了 userId, teacherName, courseName 等已不存在的字段
     * ============================================================
     */

    // @Override
    // public Long createSchedule(ScheduleSaveReqVO createReqVO) {
    //     // 获取当前登录用户ID
    //     Long userId = SecurityFrameworkUtils.getLoginUserId();
    //     
    //     // 获取用户信息
    //     AdminUserRespDTO user = adminUserApi.getUser(userId);
    //     if (user == null) {
    //         throw exception(SCHEDULE_NOT_EXISTS);
    //     }
    //     
    //     // 插入
    //     ScheduleDO schedule = BeanUtils.toBean(createReqVO, ScheduleDO.class);
    //     schedule.setUserId(userId);
    //     schedule.setTeacherName(user.getNickname());
    //     scheduleMapper.insert(schedule);
    //
    //     // 返回
    //     return schedule.getId();
    // }

    // @Override
    // public void updateSchedule(ScheduleSaveReqVO updateReqVO) {
    //     // 校验存在
    //     ScheduleDO existSchedule = validateScheduleExists(updateReqVO.getId());
    //     
    //     // 获取当前登录用户ID
    //     Long userId = SecurityFrameworkUtils.getLoginUserId();
    //     
    //     // 校验权限：只能修改自己的课程
    //     if (!existSchedule.getUserId().equals(userId)) {
    //         throw exception(SCHEDULE_NOT_EXISTS);
    //     }
    //     
    //     // 更新（保持原有的userId和teacherName）
    //     ScheduleDO updateObj = BeanUtils.toBean(updateReqVO, ScheduleDO.class);
    //     updateObj.setUserId(existSchedule.getUserId());
    //     updateObj.setTeacherName(existSchedule.getTeacherName());
    //     scheduleMapper.updateById(updateObj);
    // }

    // @Override
    // public void deleteSchedule(Long id) {
    //     // 校验存在
    //     ScheduleDO existSchedule = validateScheduleExists(id);
    //     
    //     // 获取当前登录用户ID
    //     Long userId = SecurityFrameworkUtils.getLoginUserId();
    //     
    //     // 校验权限：只能删除自己的课程
    //     if (!existSchedule.getUserId().equals(userId)) {
    //         throw exception(SCHEDULE_NOT_EXISTS);
    //     }
    //     
    //     // 删除
    //     scheduleMapper.deleteById(id);
    // }

    // @Override
    // public void deleteScheduleListByIds(List<Long> ids) {
    //     // 删除
    //     scheduleMapper.deleteByIds(ids);
    // }

    // private ScheduleDO validateScheduleExists(Long id) {
    //     ScheduleDO schedule = scheduleMapper.selectById(id);
    //     if (schedule == null) {
    //         throw exception(SCHEDULE_NOT_EXISTS);
    //     }
    //     return schedule;
    // }

    // @Override
    // public ScheduleDO getSchedule(Long id) {
    //     return scheduleMapper.selectById(id);
    // }

    // @Override
    // public PageResult<ScheduleDO> getSchedulePage(SchedulePageReqVO pageReqVO) {
    //     return scheduleMapper.selectPage(pageReqVO);
    // }

    // @Override
    // public List<ScheduleDO> getScheduleTable(String location, Integer weekNumber, String teacherName) {
    //     return scheduleMapper.selectList(location, weekNumber, teacherName);
    // }

    // @Override
    // public ScheduleConflictCheckRespVO checkConflict(ScheduleConflictCheckReqVO reqVO) {
    //     ScheduleConflictCheckRespVO respVO = new ScheduleConflictCheckRespVO();
    //     respVO.setHasConflict(false);
    //     
    //     // 查询是否存在冲突（支持排除指定ID）
    //     ScheduleDO existSchedule = scheduleMapper.selectByLocationAndTime(
    //         reqVO.getLocation(),
    //         reqVO.getDayOfWeek(),
    //         reqVO.getTimeSlot(),
    //         reqVO.getWeekNumber(),
    //         reqVO.getExcludeId()
    //     );
    //     
    //     if (existSchedule != null) {
    //         respVO.setHasConflict(true);
    //         respVO.setConflictTeacherName(existSchedule.getTeacherName());
    //         respVO.setConflictCourseName(existSchedule.getCourseName());
    //         respVO.setConflictClassName(existSchedule.getClassName());
    //         respVO.setConflictLocation(existSchedule.getLocation());
    //         respVO.setConflictDayOfWeek(existSchedule.getDayOfWeek());
    //         respVO.setConflictTimeSlot(existSchedule.getTimeSlot());
    //     }
    //     
    //     return respVO;
    // }

    @Override
    public List<String> getLocationList() {
        // 从数据库中获取所有不重复的教室
        List<String> locations = scheduleMapper.selectList()
            .stream()
            .map(ScheduleDO::getClassroom)
            .filter(classroom -> classroom != null && !classroom.isEmpty())
            .distinct()
            .sorted()
            .collect(Collectors.toList());
        
        return locations;
    }

    @Override
    public List<TeacherScheduleRespVO> getTeacherSchedule(String teacherName, String term) {
        List<TeacherScheduleRespVO> result = new ArrayList<>();
        
        // 查询所有数据行
        List<ScheduleDO> allSchedules = scheduleMapper.selectList();
        
        // 如果指定了学期,进行过滤
        if (term != null && !term.isEmpty()) {
            allSchedules = allSchedules.stream()
                .filter(s -> term.equals(s.getTerm()))
                .collect(Collectors.toList());
        }
        
        // 遍历每一行数据
        for (ScheduleDO schedule : allSchedules) {
            // 检查7天的课程
            String[] weekdayCourses = {
                schedule.getMondayCourse(),
                schedule.getTuesdayCourse(),
                schedule.getWednesdayCourse(),
                schedule.getThursdayCourse(),
                schedule.getFridayCourse(),
                schedule.getSaturdayCourse(),
                schedule.getSundayCourse()
            };
            
            for (int dayIndex = 0; dayIndex < 7; dayIndex++) {
                String courseContent = weekdayCourses[dayIndex];
                
                // 如果该天有课程内容
                if (courseContent != null && !courseContent.trim().isEmpty()) {
                    // 检查是否包含教师姓名
                    boolean isOwnCourse = courseContent.contains(teacherName);
                    
                    // 如果是查询教师自己的课表,只返回包含教师名的课程
                    if (isOwnCourse) {
                        TeacherScheduleRespVO vo = TeacherScheduleRespVO.builder()
                            .id(schedule.getId())
                            .term(schedule.getTerm())
                            .className(schedule.getClassName())
                            .classSection(schedule.getClassSection())
                            .dayOfWeek(dayIndex + 1) // 1-7 代表周一到周日
                            .courseContent(courseContent)
                            .classroom(schedule.getClassroom())
                            .isOwnCourse(true)
                            .build();
                        result.add(vo);
                    }
                }
            }
        }
        
        // 按时段排序
        result.sort((a, b) -> {
            // 先按 classSection 排序(早1, 早2, ... 或 第1节, 第2节...)
            int sectionCompare = a.getClassSection().compareTo(b.getClassSection());
            if (sectionCompare != 0) return sectionCompare;
            // 再按星期排序
            return a.getDayOfWeek().compareTo(b.getDayOfWeek());
        });
        
        return result;
    }

    @Override
    public void updateCourseContent(Long id, Integer dayOfWeek, String courseContent, String teacherName) {
        ScheduleDO schedule;
        
        if (id == null) {
            // 新增课程 - 这个逻辑需要在 Controller 层处理完整参数
            throw exception(SCHEDULE_NOT_EXISTS);
        } else {
            // 编辑现有课程
            schedule = scheduleMapper.selectById(id);
            if (schedule == null) {
                throw exception(SCHEDULE_NOT_EXISTS);
            }
            
            // 获取原有课程内容
            String originalContent = getCourseBydayOfWeek(schedule, dayOfWeek);
            
            // 权限校验：检查原课程是否属于当前教师
            if (originalContent == null || !originalContent.contains(teacherName)) {
                throw exception(SCHEDULE_NOT_EXISTS);
            }
            
            // 更新对应星期的课程内容
            updateCourseBydayOfWeek(schedule, dayOfWeek, courseContent);
            
            // 保存到数据库
            scheduleMapper.updateById(schedule);
        }
    }
    
    /**
     * 添加新课程到指定班级的指定时段
     */
    public void addNewCourseContent(String className, String classSection, Integer dayOfWeek, 
                                    String classroom, String courseContent, String teacherName) {
        // 1. 查找对应的班级和时段的数据行
        List<ScheduleDO> schedules = scheduleMapper.selectList().stream()
            .filter(s -> className.equals(s.getClassName()))
            .filter(s -> classSection.equals(s.getClassSection()))
            .collect(Collectors.toList());
        
        if (schedules.isEmpty()) {
            // 如果不存在该班级该时段的数据行,需要创建一个
            ScheduleDO newSchedule = new ScheduleDO();
            newSchedule.setClassName(className);
            newSchedule.setClassSection(classSection);
            newSchedule.setClassroom(classroom);
            
            // 设置对应星期的课程
            updateCourseBydayOfWeek(newSchedule, dayOfWeek, courseContent);
            
            scheduleMapper.insert(newSchedule);
        } else {
            // 如果存在,则更新
            ScheduleDO schedule = schedules.get(0);
            
            // 检查该星期是否已有课程
            String existingCourse = getCourseBydayOfWeek(schedule, dayOfWeek);
            if (existingCourse != null && !existingCourse.trim().isEmpty()) {
                throw exception(SCHEDULE_NOT_EXISTS); // 该时段已有课程
            }
            
            // 设置课程
            updateCourseBydayOfWeek(schedule, dayOfWeek, courseContent);
            scheduleMapper.updateById(schedule);
        }
    }

    @Override
    public String checkTimeConflict(String classSection, String classroom, Integer dayOfWeek, Long excludeId) {
        // 查询相同时段、相同教室的所有数据行
        List<ScheduleDO> schedules = scheduleMapper.selectList().stream()
            .filter(s -> classSection.equals(s.getClassSection()))
            .filter(s -> classroom.equals(s.getClassroom()))
            .filter(s -> excludeId == null || !s.getId().equals(excludeId))
            .collect(Collectors.toList());
        
        // 检查这些数据行中,对应星期几的课程是否已有教师
        for (ScheduleDO schedule : schedules) {
            String courseContent = getCourseBydayOfWeek(schedule, dayOfWeek);
            if (courseContent != null && !courseContent.trim().isEmpty()) {
                // 从课程内容中提取教师姓名(格式: "课程名/教师名" 或 "课程名")
                if (courseContent.contains("/")) {
                    String[] parts = courseContent.split("/");
                    if (parts.length > 1) {
                        return parts[1].trim(); // 返回冲突的教师姓名
                    }
                }
                return "未知教师"; // 有课程但格式不标准
            }
        }
        
        return null; // 无冲突
    }

    /**
     * 根据星期几获取课程内容
     */
    private String getCourseBydayOfWeek(ScheduleDO schedule, Integer dayOfWeek) {
        switch (dayOfWeek) {
            case 1: return schedule.getMondayCourse();
            case 2: return schedule.getTuesdayCourse();
            case 3: return schedule.getWednesdayCourse();
            case 4: return schedule.getThursdayCourse();
            case 5: return schedule.getFridayCourse();
            case 6: return schedule.getSaturdayCourse();
            case 7: return schedule.getSundayCourse();
            default: return null;
        }
    }

    /**
     * 根据星期几更新课程内容
     */
    private void updateCourseBydayOfWeek(ScheduleDO schedule, Integer dayOfWeek, String courseContent) {
        switch (dayOfWeek) {
            case 1: schedule.setMondayCourse(courseContent); break;
            case 2: schedule.setTuesdayCourse(courseContent); break;
            case 3: schedule.setWednesdayCourse(courseContent); break;
            case 4: schedule.setThursdayCourse(courseContent); break;
            case 5: schedule.setFridayCourse(courseContent); break;
            case 6: schedule.setSaturdayCourse(courseContent); break;
            case 7: schedule.setSundayCourse(courseContent); break;
        }
    }

}